<?php

namespace app\controller;


use app\BaseController;
use Exception;
use think\Request;
use think\response\Json;

use QCloud\COSSTS\Sts;

class Config extends BaseController {
    //获取上传腾讯cos的配置->五个值
    public function cos_config(Request $request): Json
    {
        try {
            $config = [
                'region' => "ap-shanghai",
                'app_id' => "1336131093",
                'secret_id' => "AKID76tUt7b4LSWRBxc8RYeXDhy1qdFfuwkL",
                'secret_key' => "TbWO7kLk3NWp3A5nLpGUgbMuFOL5dmmb",
                'bucket' => "steam",
            ];

            $sts = new Sts();
            $option = [
                'url' => 'https://sts.tencentcloudapi.com/',
                'proxy' => '',
                'secretId' => $config['secret_id'],
                'secretKey' => $config['secret_key'],
                'bucket' => $config['bucket'] . '-' . $config['app_id'],
                'region' => $config['region'],
                'durationSeconds' => 1800,
                'allowPrefix' => ['*'],
                'allowActions' => [
                    'name/cos:GetObject',
                    'name/cos:PutObject',
                    'name/cos:PostObject',
                    'name/cos:InitiateMultipartUpload',
                    'name/cos:ListMultipartUploads',
                    'name/cos:ListParts',
                    'name/cos:UploadPart',
                    'name/cos:CompleteMultipartUpload',
                ],
            ];

            try {
                $response = $sts->getTempKeys($option);

                $arr = [
                    'driver' => 'cos',
                    'secret' => [
                        'appId' => $config['app_id'],
                        'bucket' => $config['bucket'],
                        'region' => $config['region'],
                        'startTime' => $response['startTime'],
                        'expiredTime' => $response['expiredTime'],
                        'expiration' => $response['expiration'],
                        'credentials' => $response['credentials'],
                    ],
                ];
                return json(['code' => 0, 'msg' => 'success', 'data' => $arr]);

            } catch (Exception $exception) {
                throw new Exception('密钥生成失败');
            }
            return json(['code' => 0, 'msg' => 'success', 'data' => $config]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => '服务繁忙,请稍后再试']);
        }
    }
}
